package utils

import (
	// "database/sql"
	"github.com/garyburd/redigo/redis"
	_ "github.com/go-sql-driver/mysql"
	// "log"
	// "strconv"
	"time"
)

type RedisPool struct {
	pool *redis.Pool
	conf Config
}

//根据配置文件内的redis连接池
func NewRedisPoolFromConfig() (rrp *RedisPool) {
	return NewRedisPool(conf.Redis.Host+":"+conf.Redis.Port, conf.Redis.Pswd, conf.Redis.Database, conf.Redis.Timeout)
}

//新建一个redis连接池
func NewRedisPool(server string, password string, database string, timeout int) (rrp *RedisPool) {
	rp := new(RedisPool)
	rp.pool = &redis.Pool{
		MaxIdle:     5,
		IdleTimeout: time.Duration(timeout) * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}

			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}

			if database != "" {
				if _, err := c.Do("SELECT", database); err != nil {
					c.Close()
					return nil, err
				}
			}

			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
	return rp
}

//获得连接总数
func (rp *RedisPool) ActionCount() int {
	return rp.pool.ActiveCount()
}

//执行redis命令
func (rp *RedisPool) Do(cmd string, args ...interface{}) (reply interface{}, err error) {
	conn := rp.pool.Get()
	defer conn.Close()
	return conn.Do(cmd, args...)
}

//关闭连接池
func (rp *RedisPool) Close() {
	rp.pool.Close()
}
